Skip to content

ADP-2219:Flat collection custom metrics - #332

Open
KIRTIKUMARKK21 wants to merge 5 commits into
mainfrom
flat-collection-custom-metrics
Open

KIRTIKUMARKK21 wants to merge 5 commits into
mainfrom
flat-collection-custom-metrics

Conversation

@KIRTIKUMARKK21

@KIRTIKUMARKK21 KIRTIKUMARKK21 commented Dec 3, 2026 •

Copy link
Copy Markdown

Description

Support custom metrics on flat Postgres collections

Why

DocStoreMetricsRegistry custom metrics are currently hard-wired to nested
collections. BaseDocStoreMetricProviderImpl.getCustomMetrics resolves the
target collection with dataStore.getCollection(collectionName), and on
Postgres that factory always returns a NestedPostgresCollection — a table
with a single JSONB document column. Worse, for Postgres it will create the
nested table if it does not already exist.

That makes it impossible to report a custom metric from a flat Postgres table
(one real column per attribute, native TEXT[] / BIGINT / BOOLEAN
columns). Any attempt either fails to find the columns or silently points at
an empty, freshly created nested table.

This blocks entity-service: API and other entity types that have moved to
Postgres now live in flat tables (entities_api_v1 and friends), so their
metrics — api.entities.count, real.entities.discovered.count, and the rest
— cannot be reported from the store the data actually lives in. Dashboards for
migrated tenants are stale as a result.

What changed

1. CustomMetricConfig carries the document type

Added a documentType field, defaulted to DocumentType.NESTED:

@NonNull @Builder.Default DocumentType documentType = DocumentType.NESTED;

The default keeps every existing caller behaving exactly as before — this is a
source- and behaviour-compatible addition.

2. BaseDocStoreMetricProviderImpl resolves the collection by type

getCustomMetrics no longer calls getCollection unconditionally. It now
routes through a small helper:

private Collection getCollection(final CustomMetricConfig customMetricConfig) {
  if (customMetricConfig.documentType() == DocumentType.NESTED) {
    return dataStore.getCollection(customMetricConfig.collectionName());
  }
  return dataStore.getCollectionForType(
      customMetricConfig.collectionName(), customMetricConfig.documentType());
}

NESTED deliberately keeps using the original getCollection path rather than
getCollectionForType(name, NESTED) so that existing nested-collection
behaviour, including Mongo, is bit-for-bit unchanged.

No changes were needed in the query layer: FlatPostgresFieldTransformer
already treats a dotted identifier such as attributes.apiDiscoveryState as a
literal quoted column name, and PostgresFromTypeExpressionVisitor already
emits a native unnest() for array columns on flat collections rather than
jsonb_array_elements(). Once the right Collection implementation is
selected, grouped counts and unnested-array counts work as-is.

Tests

Unit — BaseDocumentStoreMetricProviderImplTest

New CollectionResolutionTest nested class covering the routing decision:

  • nestedDocumentType_usesGetCollection — asserts getCollection is used and
    getCollectionForType is never touched.
  • flatDocumentType_usesGetCollectionForType — asserts the flat path resolves
    through getCollectionForType(name, FLAT), never getCollection, and that
    the resulting rows are still mapped into DocStoreMetric with the correct
    name, value, and labels.
  • defaultDocumentType_isNested — pins the backwards-compatible default.

Integration — FlatCollectionWriteTest

New CustomMetricTests nested class running against a real Postgres flat
table:

  • testGroupedCountOnFlatColumns — a COUNT(*) GROUP BY item custom metric
    over plain flat columns, asserting both the metric name and the per-label
    counts.
  • testUnnestedArrayCount — a custom metric that groups over an unnest()ed
    TEXT[] column (categoryTags), which is the shape the entity-service
    category and discovery-source metrics need.

Compatibility

Fully backwards compatible. documentType defaults to NESTED, so every
existing CustomMetricConfig builder call compiles unchanged and resolves its
collection exactly as it does today.

Follow-up

entity-service will consume this to report entity metrics from whichever store
a tenant's read-write feature flag points at: flat Postgres entities_<type>_v1
for migrated tenants, Mongo raw_entities otherwise, with metric names and
labels unchanged so dashboards and the api-count-metrics-exporter need no edits.

Checklist:

  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • Any dependent changes have been merged and published in downstream modules

Documentation

Make sure that you have documented corresponding changes in this repository or hypertrace docs repo if required.

KIRTIKUMARKK21 and others added 2 commits December 3, 2026 12:06
Co-authored-by: Cursor <cursoragent@cursor.com>
@codecov

codecov Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 81.27%. Comparing base (73cbdc2) to head (9851593).

Additional details and impacted files
@@             Coverage Diff              @@
##               main     #332      +/-   ##
============================================
+ Coverage     81.25%   81.27%   +0.02%     
- Complexity     1700     1703       +3     
============================================
  Files           243      243              
  Lines          7792     7796       +4     
  Branches        773      773              
============================================
+ Hits           6331     6336       +5     
+ Misses          961      960       -1     
  Partials        500      500              
Flag Coverage Δ
integration 81.27% <100.00%> (+0.02%) ⬆️
unit 58.92% <100.00%> (+0.02%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@github-actions

github-actions Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

Test Results

  130 files  +2    130 suites  +2   33s ⏱️ -9s
  905 tests +5    904 ✅ +5  1 💤 ±0  0 ❌ ±0 
1 275 runs  +5  1 274 ✅ +5  1 💤 ±0  0 ❌ ±0 

Results for commit 9851593. ± Comparison against base commit 73cbdc2.

♻️ This comment has been updated with latest results.

KIRTIKUMARKK21 and others added 2 commits December 3, 2026 13:50
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>

@suddendust suddendust left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

Co-authored-by: Cursor <cursoragent@cursor.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants